package com.xuzimian.opencv.demo;

import nu.pattern.OpenCV;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;

import java.io.File;
import java.nio.file.Paths;

public class ShowInGuiDemo {

    public static void showInGUI(String rtspUri) throws IllegalAccessException {
        System.setProperty("OPENCV_FFMPEG_CAPTURE_OPTIONS", "rtsp_transport;tcp");
        OpenCV.loadLocally();
        String info = Core.getBuildInformation();
        VideoCapture cap = new VideoCapture(rtspUri); // Videoio.CAP_FFMPEG

        System.out.println(info);
        if (!cap.isOpened()) {
            System.out.println("Cannot open RTSP stream");
            System.exit(-1);
        }

        Mat frame = new Mat();
        while (true) {
            cap.read(frame);
            HighGui.imshow("RTSP stream", frame);

            if (HighGui.waitKey(1) == 27) {
                break;
            }
        }

        cap.release();
        HighGui.destroyAllWindows();

        System.exit(0);
    }


    public void openRTSP(boolean isOpened, VideoCapture capturedVideo, Mat cameraMat) {
        if (isOpened) {
            boolean tempBool = capturedVideo.read(cameraMat);
            System.out.println("VideoCapture returned mat? " + tempBool);

            if (!cameraMat.empty()) {
                System.out.println("Print image size: " + cameraMat.size());
                //processing image captured in cameraMat object

            } else {
                System.out.println("Mat is empty.");
            }
        } else {
            System.out.println("Camera connection problem. Check addressString");
        }
    }

    private static void loadExternalLibs() {

        File[] files = Paths.get("libs/opencv_python.libs/").toAbsolutePath().toFile().listFiles();
        for (File file : files) {
            try {
                System.out.print("------------加载----------:" + file.getName());
                System.load(file.getAbsolutePath());
                System.out.println("   成功 ");
            } catch (UnsatisfiedLinkError e) {
                System.out.print("   失败 ");
                System.out.println();
            }

        }

        files = Paths.get("libs/numpy.libs/").toAbsolutePath().toFile().listFiles();
        for (File file : files) {
            try {
                System.out.print("------------加载----------:" + file.getName());
                System.load(file.getAbsolutePath());
                System.out.println("   成功 ");
            } catch (UnsatisfiedLinkError e) {
                System.out.print("   失败 ");
                System.out.println();
            }

        }
    }
}
